import React from "react";
import Button from 'bee-button';
import 'bee-button/build/Button.css';

import { Icon, Label, Row, Col , Upload, Checkbox} from 'tinper-bee';

import Switch from 'bee-switch';
import 'bee-switch/build/Switch.css';

import FormControl from "bee-form-control";
import 'bee-form-control/build/FormControl.css';

import multiSelect from "bee-table/build/lib/multiSelect";
import Table from 'bee-table';
import 'bee-table/build/Table.css';
import sort from "bee-table/build/lib/sort";
let ComplexTable = multiSelect(sort(Table, Icon), Checkbox);

import "../common/index.less";
import { buttonClick, onRowDoubleClick, getSelectedDataFunc, onChange, RenderHtml, linkTo, queryCard, addOperationCol, empowerClick } from "./../common/index.js";
import { ButtonConfig } from "./../common/const.js";
import { vendorsWarning as warning } from './../../../utils/config.js';

import createYGCPage from "./../../../components/CreateYGCPage/index.jsx";
import billIcon from './../../../assets/icon/ygc_stop_work.png';
import { FormItems, btnCardTpl, treemodalTpl, getUploadConfig } from "./../tpl/index.js";
const {
    CardEditTableHeadButtons,
    CardFilesButtons
} = ButtonConfig;
import YGCreateModalTree from "./../../../components/YGCreateModalTree/index.jsx";

@createYGCPage()
export default class Edit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            status: '',
            pk: '',
            cancelModal: false,
            columns: [
                {
                    title: "序号", dataIndex: "index", key: "index", width: "5%", render: (text, record, index) => {
                        return index + 1;
                    }
                },
                {
                    title:  <div>
                                <span style={{color: 'red'}}>*</span>
                                人员名称
                            </div>, 
                    required: true, dataIndex: "sname", key: "sname", render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'sname', value: text })}
                            </div>
                        )
                    }
                },
                {
                    title: "手机号码", dataIndex: "phone", key: "phone", render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'phone', value: text })}
                            </div>
                        )
                    }
                },
                {
                    title: "邮箱", dataIndex: "email", key: "email", render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'email', value: text })}
                            </div>
                        )
                    }
                },
                {
                    title: "企业联系人", dataIndex: "isContacts", key: "isContacts", sorter: (a, b) => a.isContacts - b.isContacts, render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'isContacts', value: text })}
                            </div>
                        )
                    }
                },
                {
                    title: "是否特殊工种", dataIndex: "isSpecialWork", key: "isSpecialWork", render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'isSpecialWork', value: text })}
                            </div>
                        )
                    }
                },
                {
                    title: "友工程权限", dataIndex: "isYgcAuthorizer", key: "isYgcAuthorizer", sorter: (a, b) => a.isYgcAuthorizer - b.isYgcAuthorizer, render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'isYgcAuthorizer', value: text })}
                            </div>
                        )
                    }
                },
                {
                    title: "备注", dataIndex: "memo", key: "memo", render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'memo', value: text })}
                            </div>
                        )
                    }
                },
                {
                    title: "用户", dataIndex: "userName", key: "userName", render: (text, record, index) => {
                        return (
                            <div>
                                {record && this.formControl(text, record, index, { key: 'userName', value: text })}
                            </div>
                        )
                    }
                },
            ],
            initData: { tableData: [] },
            selectedTableData: [],
            tableData: [],
            orgData: [],
            buttonIdCur: '',
            deleteTableS: [],
            // pkOrgs: [],
          //  orgNames: [],
            // orgItems: []
        }

        this.onRowDoubleClick = onRowDoubleClick.bind(this);
        this.getSelectedDataFunc = getSelectedDataFunc.bind(this);
        this.formItems = FormItems.call(this);
        this.btnCardTpl = btnCardTpl;
        this.initTplAfter = this.initTplAfter.bind(this)
        this.treemodalTpl = treemodalTpl.call(this);
        this["empower"] = false;

    }

    onChange = (checked = false, index, key) => {
        this.state.tableData[index][key] = checked;
        onChange.call(this, { tableData: [...this.state.tableData] })

    }

    formControl = (text, record, index, curObj) => {

        let {
            status,
            tableData
        } = this.state;

        if (status === "browse") {
            if (curObj.key === 'isContacts' || curObj.key === 'isSpecialWork') {
                return (
                    <div className={'attrStyle'}>{curObj.value ? "是" : "否"}</div>
                )
            } else if (curObj.key === 'isYgcAuthorizer') {
                return (
                    <Switch
                        checked={curObj.value}
                        disabled={false}
                        onChange={(value) => {
                            tableData[index][curObj.key] = value;

                            if (curObj.key === "isYgcAuthorizer") {
                                let realAuthorizedNum = this.props.form.getFormItemValue('realAuthorizedNum') && this.props.form.getFormItemValue('realAuthorizedNum').value || 0;
                                let planAuthorizedNum = this.props.form.getFormItemValue('planAuthorizedNum') && this.props.form.getFormItemValue('planAuthorizedNum').value || 0;
                                if (value) {
                                    realAuthorizedNum++
                                } else {
                                    realAuthorizedNum--
                                }
                                if (realAuthorizedNum > planAuthorizedNum) {
                                    warning({ text: `实际授权数不得超过计划授权数` });
                                    tableData[index][curObj.key] = !value;
                                    return

                                }
                                if (!record.sname) {
                                    warning({ "text": "人员名称为空不得进行授权或取消授权操作" })
                                    tableData[index][curObj.key] = !value
                                    return
                                } else if (!record.phone && !record.email) {
                                    warning({ "text": "人员手机号或邮箱为空不得进行授权或取消授权操作" })
                                    tableData[index][curObj.key] = !value
                                    return
                                }
                                //防止重复点击
                                if (!value === !record.isYgcAuthorizer) {//一个是boolean一个是number所以加！
                                    return
                                }
                                record.isYgcAuthorizer = !value //成功之后在去控制按钮变化，现做的是，通过再次查询。。。
                                if (value) {
                                    buttonClick.call(this, 'EmpowerRow', record)
                                } else {
                                    buttonClick.call(this, 'UnEmpowerRow', record)
                                }
                                return;
                            } else {
                                this.setState({
                                    tableData: [...tableData]
                                })
                            }

                        }}
                    />
                )
            } else {
                return (
                    <div className={'attrStyle'}>{curObj.value}</div>
                )
            }
        } else if (status !== "browse") {

            if (curObj.key === 'isContacts' || curObj.key === 'isSpecialWork' || curObj.key === 'isYgcAuthorizer') {
                return (
                    <Switch
                        checked={curObj.value}
                        disabled={curObj.key === 'isYgcAuthorizer' && status !== "browse" ? true : status === "browse" ? false : curObj.disabled}
                        onChange={(value) => {
                            tableData[index][curObj.key] = value;
                            if (curObj.key === "isYgcAuthorizer") {
                                if (!record.sname) {
                                    warning({ "text": "请填写人员名称" })
                                    tableData[index][curObj.key] = !value
                                    return
                                } else if (!record.phone && !record.email) {
                                    warning({ "text": "请填写人员手机号或邮箱" })
                                    tableData[index][curObj.key] = !value
                                    return
                                }
                                record.isYgcAuthorizer = value
                                if (value) {
                                    buttonClick.call(this, 'EmpowerRow', record)
                                } else {
                                    buttonClick.call(this, 'UnEmpowerRow', record)
                                }
                                return;
                            } else {
                                this.setState({
                                    tableData: [...tableData]
                                })
                            }

                        }}
                    />
                )
            } else {
                return (
                    <div
                        className={'attrStyle'}
                    >
                        {
                            this.inputTableHtml(index, curObj, record)
                        }
                    </div>
                )
            }

        }
    }

    //table的编辑输入框形态
    inputTableHtml = (index, curObj, record) => {
        let {
            tableData,
            initData
        } = this.state
        return (
            <FormControl
                value={curObj.value}
                ref={(input) => { this[curObj.key] = input }}
                onBlur={
                    (e) => {
                        let value = e && e.target && e.target.value ||e ;
                        if (curObj.key === "email") {
                            let _this = this;

                            if (value) {
                                let exp = new RegExp(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g);
                                let flag = exp.test(value);

                                if (!flag) {
                                    warning({ 'text': "请输入有效邮箱" })
                                    tableData[index][curObj.key] = '';
                                    onChange.call(this, {
                                        tableData: [...tableData],
                                    })
                                    return;
                                }
                            }
                        }
                        if (curObj.key === "phone") {
                            let _this = this;

                            if (value) {
                                let exp = new RegExp(/^\d{11}$/g);
                                let flag = exp.test(value);
                               
                                if (!flag) {
                                    warning({ 'text': "请输入有效手机号" })
                                    tableData[index][curObj.key] = '';
                                    onChange.call(this, {
                                        tableData: [...tableData],
                                    })
                                    return;
                                }
                            }
                        }
                        if(curObj.key === "email" || curObj.key === "phone"){
                            if(initData["tableData"].find((item, )=>{
                                return (item.pkPersonnel === record.pkPersonnel) && record.pkPersonnel
                            })){
                                warning({ 'text': `你修改的${curObj.value}的${curObj.key === "phone" ? "手机号": "邮箱"}，不改变用户登录账号，请知晓` })  
                            }
                        }
                        

                    }

                }
                onChange={(e) => {
                    let value = e && e.target && e.target.value ||e ;
                    if (value) {


                        tableData[index][curObj.key] = value;

                    } else {
                        tableData[index][curObj.key] = '';

                    }
                    onChange.call(this, {
                        tableData: [...tableData],
                    })
                }}
                disabled={curObj.key === "userName" ? true : false}
            />
        )
    }

    initTplAfter() {
        this.props.button.setButtonState(this.state.status);
        this.props.form.setFormStatus(this.state.status);

        if (this.state.status !== 'add' && this.state.pk) {
            queryCard.call(this, { pkEnterprise: this.state.pk }, true);
        }

        addOperationCol.call(this)
    }

    componentDidMount() {

        let {
            status = "",
            pk = ''
        } = this.props.location && this.props.location.state;
        window.addEventListener("load", (e) => {

            if (this.state.status) {
                status = this.state.status,
                    pk = this.state.pk
            }

        })

        this.setState({
            status,
            pk,
        })
    }

    handleEmptyItem = (dataSource) =>{
        this.modalTreeC.output.clearSelectDataByDataSouce(dataSource);
        //为的是渲染moaltree树组件后， 也渲染一下本组件， 要不清不掉
        this.setState({

        })
    }


    render() {
        let {
            columns,
            status,
            tableData,
            selectedTableData
        } = this.state;
        return (
            <div className="ygc-card card">
                <div id="header" className="ygc-card-header ">
                    <div className=" header-title">
                        {this.props.YGCreateCardTitle({
                            title: '人员管理',
                            billIcon,
                            backRoute: linkTo.bind(this, "/list"),
                            pageStatus: this.state.status
                        })}
                    </div>
                    <div className='ygc-card-header-button header-button'>
                        {this.props.YGCreateButton({
                            btnTpl: btnCardTpl,
                            buttonClick: (key) => buttonClick.call(this, Object.values(key)[0])
                        })}
                        <div className = {'btn-box'}>
                            {/* {RenderHtml['headerButton'].call(this, status !== "browse" ? CardFilesButtons: [])}*下载模板， 先煮掉 */}
                            <Button
                                bordered = {true}
                                style = {{
                                     // display :this.state.status === "edit" ? "flex": 'none'
                                    display :'none'
                                }}
                            >
                                <Upload  {...getUploadConfig.call(this)}>
                                    导入人员
								</Upload>
                            </Button>
                    
                        </div>
                    </div>
                </div>
                <div id="table" className=" ygc-card-body table common">
                    {this.props.YGCCreateForm(this.formItems)}
                  
                    <Row className={'ygc-form-container'}>
                        <div className="u-row">
                            <Col md={12} xs={12} sm={12} >
                                <div className="form-panel-item">
                                    <div className='form-panel-item-label'>{/**公共组件 */}
                                        组织范围：
                                    </div>
                                    {
                                        status === "browse" ?
                                            <div  className={`form-panel-item-control `} style={{display:'flex', alignItems:'center'}}>{
                                                this.modalTreeC&& this.modalTreeC.output.getSelectDataByDataSouce("personnelFiles_modalOrgTree_form_area").name.toString() ||''
                                            }</div>
                                            :
                                            < div className={`form-panel-item-control `}>
                                                <FormControl
                                                    className={`ref-input`}
                                                    value={ this.modalTreeC&& this.modalTreeC.output.getSelectDataByDataSouce("personnelFiles_modalOrgTree_form_area").name ||''}
                                                />
                                                <Icon type='uf-navmenu'
                                                    className='form-panel-item-input-icon'
                                                    onClick={() => { this.modalTreeC.output.isShow("personnelFiles_modalOrgTree_form_area") }}
                                                />
                                                {
                                                    this.modalTreeC&& this.modalTreeC.output.getSelectDataByDataSouce("personnelFiles_modalOrgTree_form_area").name.length ?
                                                        <Icon className='item-empty-icon' type="uf-close-c-o" onClick={() => {
                                                            this.handleEmptyItem('personnelFiles_modalOrgTree_form_area')
                                                        }} /> :
                                                    null
                                                }
                                            </div>

                                    }

                                </div>
                            </Col>
                        </div>


                    </Row>
                    {YGCreateModalTree.call(this, { ...this.treemodalTpl })}

                    <div className="ygc-card-body-table">
                        <div className={'header-title '}>
                            <span>人员列表</span>
                            <div>
                                {RenderHtml['headerButton'].call(this, status !== "browse" ? selectedTableData ? CardEditTableHeadButtons : CardEditTableHeadButtons : [])}
                            </div>
                        </div>
                        <div>
                            <ComplexTable
                                height={50}
                                columns={columns}
                                data={tableData}
                                multiSelect={{ type: "checkbox" }}
                                emptyText={() => { return "暂无数据" }}
                                sort={{ mode: 'multiple' }}
                                getSelectedDataFunc={(selectedList, record, index, newData) => this.getSelectedDataFunc(selectedList, record, index, newData , "selectedTableData")}
                                className = {"complex-table"}
                            />
                        </div>
                    </div>

                </div>
            </div>
        )
    }
}